package map;

import java.io.FileNotFoundException;
import java.util.ArrayList;

import binaryTree.avl.CandyAVLTree;
import util.FileOperation;

/**
 * 
 * @Title: CandyBSTMap.java 
 * @Package map 
 * @Description: 基于平衡二叉树的映射实现
 * @author CandyWall   
 * @date 2021年1月6日 下午4:34:39 
 * @version V1.0
 */
public class CandyAVLMap<K extends Comparable<K>, V> implements CandyMap<K, V> {
    private CandyAVLTree<K, V> avlTree;
    public CandyAVLMap() {
        avlTree = new CandyAVLTree<>();
    }

    @Override
    public void add(K key, V value) {
        avlTree.add(key, value);
    }

    @Override
    public V remove(K key) {
        return avlTree.remove(key);
    }

    @Override
    public boolean contains(K key) {
        return avlTree.contains(key);
    }

    @Override
    public V get(K key) {
        return avlTree.get(key);
    }

    @Override
    public void set(K key, V newValue) {
        avlTree.set(key, newValue);
    }

    @Override
    public int getSize() {
        return avlTree.getSize();
    }

    @Override
    public boolean isEmpty() {
        return avlTree.isEmpty();
    }
    
    // 完成词频统计，返回每个单词和对应出现的次数
    public static CandyAVLMap<String, Integer> wordCount(ArrayList<String> words) {
        CandyAVLMap<String, Integer> wordCountMap = new CandyAVLMap();
        for(String word : words) {
            // 如果映射中不包含这个单词，说明这个单词第1次出现，
            // 那么将这个单词添加到映射中
            if(!wordCountMap.contains(word)) {
                wordCountMap.add(word, 1);
            } else {
                wordCountMap.set(word, wordCountMap.get(word) + 1);
            }
        }
        return wordCountMap;
    }
    
    // 从文件中读取到所有的单词，并以ArrayList<String>方式返回
    private static ArrayList<String> readWordsFromFile(String filePath) {
        ArrayList<String> words = new ArrayList<>();
        if(!FileOperation.readFile(filePath, words)) {
            // 加载失败
            try {
                throw new FileNotFoundException("找不到文件");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        } 
        return words;
    }
    
    public static void main(String[] args) {
        ArrayList<String> list = readWordsFromFile("testData/pride-and-prejudice.txt");
        CandyAVLMap<String, Integer> wordCountMap = wordCount(list);
        // wordCountMap.printMap();
        System.out.println("单词总数：" + list.size());
        System.out.println("不同单词数量：" + wordCountMap.getSize());
        System.out.println("pride出现的次数：" + wordCountMap.get("pride"));
        System.out.println("prejudice出现的次数：" + wordCountMap.get("prejudice"));
    }
}
